<?php

namespace addons\epay\controller;

use addons\epay\library\Service;
use addons\shopro\controller\Pay;
use addons\shopro\service\pay\PayOper;
use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\order\Order as OrderModel;
use app\admin\model\shopro\Pay as PayModel;
use fast\Http;
use fast\Random;
use think\addons\Controller;
use Exception;
use think\Log;
use think\Request;

/**
 * 微信支付宝整合插件首页
 *
 * 此控制器仅用于开发展示说明和测试，请自行添加一个新的控制器进行处理返回和回调事件，同时删除此控制器文件
 *
 * Class Index
 * @package addons\epay\controller
 */
class Index extends Controller
{

    protected $layout = 'default';

    protected $config = [];

    public function _initialize()
    {
        parent::_initialize();
  /*      if (!config("app_debug")) {
            $this->error("仅在开发环境下查看");
        }*/

    }

    public function index()
    {
        $this->view->assign("title", "微信支付宝整合");
        return $this->view->fetch();
    }

    /**
     * 体验，仅供开发测试
     */
    public   function  experience($order_data)
    {
        $amount = $order_data['total_amount'];
        $type =  $order_data['type'];
        $method = $order_data['method'];
     /*   if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }

        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("支付类型不能为空");
        }*/

        //订单号
        $out_trade_no =$order_data['order_sn'];
        //订单标题
        $title ="商城订单支付";
        //回调链接
        $notifyurl = $this->request->root(true). "/addons/epay/index/notifyx/paytype/wechat";
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;

        $response = Service::submitOrder($amount, $out_trade_no, $type, $title, $notifyurl, $returnurl, $method);
        return $response;
    }

    /**
     * 体验，仅供开发测试
     */
    public   function  rujinpay($order_data)
    {
        $amount = $order_data['total_amount'];
        $type =  $order_data['type'];
        $method = $order_data['method'];
        //订单号
        $out_trade_no =$order_data['order_sn'];
        //订单标题
        $title ="商城订单支付";
        //回调链接
        $notifyurl = $this->request->root(true). "/addons/epay/index/notifyx_rujin/paytype/wechat";
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;

        $response = Service::submitOrder($amount, $out_trade_no, $type, $title, $notifyurl, $returnurl, $method);
        return $response;
    }   /**
     * 体验，仅供开发测试
     */
    public   function  shande($order_data)
    {
        $amount = $order_data['total_amount'];
        $type =  $order_data['type'];
        $method = $order_data['method'];
        //订单号
        $out_trade_no =$order_data['order_sn'];
        $platform =$order_data['platform'];

        //订单标题
        $title ="商城订单支付";
        //回调链接
        $notifyurl = $this->request->root(true). "/addons/epay/index/notifyxshande/paytype/shande";
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;
        $a = new YunPayment();
        \think\Log::info($platform);

        $response = $a->dopayment($amount,$type,$method,$out_trade_no,$title,$notifyurl,$platform);

      //  \think\Log::info($response);
 /*       $response=json_encode($response);*/
       // print_r($response);exit;
        return $response;
    }

    /**
     * 支付成功，仅供开发测试
     */
    public function notifyx()
    {

        $xml = file_get_contents('php://input');
        file_put_contents(__DIR__.'/wechat.txt',$xml."\r\n",FILE_APPEND);


        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();
        try {
        //    Log::write('pay-notify-origin-data：' . json_encode($data));
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];

            $order=db('shopro_order')->where('order_sn',$out_trade_no)->find();
            if(empty($order)){
                echo '订单不存在';
                \think\Log::info( '订单不存在');
                return;
            }
            if($order['order_amount']!=$payamount){
                echo '订单支付金额不正确';
                \think\Log::info( '订单支付金额不正确');
                return;
            }
            //你可以在此编写订单逻辑
            //
            if (strpos($out_trade_no, 'TO') === 0) {
                // 交易订单
                $order_type = 'trade_order';
            } else {
                // 订单
                $order_type = 'order';
            }

            if(!empty($order)){

                $payOper = new PayOper();
                $order = OrderModel::where('id', $order['id'])->find();
                // 添加支付记录
                $payModel = new PayModel();
                $payModel->order_type =$order_type;
                $payModel->order_id = $order['id'];
                $payModel->pay_sn = get_sn($order['user_id'], 'P');
                $payModel->user_id = $order['user_id'];
                $payModel->pay_type = 'wechat';
                $payModel->pay_fee = $payamount;
                $payModel->real_fee =$payamount;
                $payModel->transaction_id = null;
                $payModel->payment_json = [];
                $payModel->paid_time = 'paid'== PayModel::PAY_STATUS_PAID ? time() : null;
                $payModel->status ='paid';
                $payModel->refund_fee = 0;
                $payModel->save();

                $payOper->checkAndPaid($order,$order_type);
            }

            // 支付成功后续使用异步队列处理
           // \think\Queue::push('\addons\shopro\job\OrderPaid@paid', ['order' => $order, 'user' => $user], 'shopro-high');

        } catch (Exception $e) {
           // var_dump($e->getMessage());
        }

        //下面这句必须要执行,且在此之前不能有任何输出

        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }   /**
     * 支付成功，仅供开发测试
     */

    public function publicKey()
    {
        try {
            $file = file_get_contents(__DIR__.'/../certs/sand.cer');
            if (!$file) {
                throw new \Exception('getPublicKey::file_get_contents ERROR');
            }
            $cert   = chunk_split(base64_encode($file), 64, "\n");
            $cert   = "-----BEGIN CERTIFICATE-----\n" . $cert . "-----END CERTIFICATE-----\n";
            $res    = openssl_pkey_get_public($cert);
            $detail = openssl_pkey_get_details($res);
            openssl_free_key($res);
            if (!$detail) {
                throw new \Exception('getPublicKey::openssl_pkey_get_details ERROR');
            }
            return $detail['key'];
        } catch (\Exception $e) {
            throw $e;
        }
    }
     public function verify($plainText, $sign)
    {
        $path=$this->publicKey();
        $resource = openssl_pkey_get_public($path);
        $result   = openssl_verify($plainText, base64_decode($sign), $resource);
        openssl_free_key($resource);
        if (!$result) {
            throw new \Exception('签名验证未通过,plainText:' . $plainText . '。sign:' . $sign, '02002');
        }

    }
    public function notifyxshande()
    {

        $data = file_get_contents('php://input');
      //  $data=input('data');
        file_put_contents(__DIR__.'/shande.txt',$data."\r\n",FILE_APPEND);

        parse_str($data,$arr);
     //   print_r($arr);exit;
      //  $data = json_decode($arr['data'], true);

        $this->verify($arr['data'], $arr['sign']);
        $data = json_decode($arr['data'], true);
     /*   echo $data['body']['totalAmount'];
         var_dump($data);exit;*/
        $payamount =intval($data['body']['totalAmount']) / 100;
        $out_trade_no = $data['body']['orderCode'];
        if (strpos($out_trade_no, 'RJ') === 0) {
            try {
                //    Log::write('pay-notify-origin-data：' . json_encode($data));
            //    $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
             //   $out_trade_no = $data['out_trade_no'];

                $order=db('shopro_chongzhi')->where('pay_sn',$out_trade_no)->find();
                if(empty($order)){
                    echo '订单不存在';
                    \think\Log::info( '订单不存在');
                    return;
                }
                if($order['pay_fee']!=$payamount){
                    echo '订单支付金额不正确';
                    \think\Log::info( '订单支付金额不正确');
                    return;
                }
                //你可以在此编写订单逻辑
                if(!empty($order)){
                    $user=db('user')->where('id',$order['user_id'])->find();
                    if($order['type']==1){
                        WalletService::change($user['id'], 'commission', $payamount, 'churujin', [
                            'mobile' => $user['mobile'],
                        ],'入金');
                    }else{
                        $time=time();
                        $sign=base64_encode(md5($user['mobile'].$time.$payamount.'haibeisign159'));//验证方式
                        $time=strval($time);
                        $params=array(
                            'amount'=>$payamount,
                            'sign'=>$sign,
                            'time'=>$time,
                            'mobile'=>$user['mobile'],
                        );
                        $arr=json_encode($params);
                        $headers=array(
                            'Content-Type:application/json',
                            'Content-Length:'.strlen($arr),
                        );
                        $ret = Http::httpRequest('https://newhb.nfttop123.com:44303/api/app/member-card-client/store-chujin', 'POST',$arr,$headers);
                        // $ret = Http::sendRequest('https://hb.nfttop123.com:44303/api/app/member-card-client/store-chujin', $params, 'POST');
                        json_decode($ret,true);
                    }

                    db('shopro_chongzhi')->where('pay_sn',$out_trade_no)->update(['status'=>'paid']);

                }

                // 支付成功后续使用异步队列处理
                // \think\Queue::push('\addons\shopro\job\OrderPaid@paid', ['order' => $order, 'user' => $user], 'shopro-high');

            } catch (Exception $e) {
                // var_dump($e->getMessage());
            }
        } else {
            try {
                //    Log::write('pay-notify-origin-data：' . json_encode($data));

                $order=db('shopro_order')->where('order_sn',$out_trade_no)->find();
                if(empty($order)){
                    echo '订单不存在';
                    \think\Log::info( '订单不存在');
                    return;
                }
                if($order['order_amount']!=$payamount){
                    echo '订单支付金额不正确';
                    \think\Log::info( '订单支付金额不正确');
                    return;
                }
                if($order['status']=='paid'){
                    echo '订单已支付';
                    return;
                }
                //你可以在此编写订单逻辑
                //
                if (strpos($out_trade_no, 'TO') === 0) {
                    // 交易订单
                    $order_type = 'trade_order';
                } else {
                    // 订单
                    $order_type = 'order';
                }

                if(!empty($order)){

                    $payOper = new PayOper();
                    $order = OrderModel::where('id', $order['id'])->find();
                    // 添加支付记录
                    $payModel = new PayModel();
                    $payModel->order_type =$order_type;
                    $payModel->order_id = $order['id'];
                    $payModel->pay_sn = get_sn($order['user_id'], 'P');
                    $payModel->user_id = $order['user_id'];
                    $payModel->pay_type = 'wechat';
                    $payModel->pay_fee = $payamount;
                    $payModel->real_fee =$payamount;
                    $payModel->transaction_id = null;
                    $payModel->payment_json = [];
                    $payModel->paid_time = 'paid'== PayModel::PAY_STATUS_PAID ? time() : null;
                    $payModel->status ='paid';
                    $payModel->refund_fee = 0;
                    $payModel->save();

                    $payOper->checkAndPaid($order,$order_type);
                }

                // 支付成功后续使用异步队列处理
                // \think\Queue::push('\addons\shopro\job\OrderPaid@paid', ['order' => $order, 'user' => $user], 'shopro-high');

            } catch (Exception $e) {
                // var_dump($e->getMessage());
            }
        }

        return "respCode=000000";
        //下面这句必须要执行,且在此之前不能有任何输出

       /* if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }*/
    }
 /**
     * 支付成功，仅供开发测试
     */
    public function notifyx_rujin()
    {

        $xml = file_get_contents('php://input');
        file_put_contents(__DIR__.'/wechat.txt',$xml."\r\n",FILE_APPEND);


        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();
        try {
        //    Log::write('pay-notify-origin-data：' . json_encode($data));
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];

            $order=db('shopro_chongzhi')->where('pay_sn',$out_trade_no)->find();
            if(empty($order)){
                echo '订单不存在';
                \think\Log::info( '订单不存在');
                return;
            }
            if($order['pay_fee']!=$payamount){
                echo '订单支付金额不正确';
                \think\Log::info( '订单支付金额不正确');
                return;
            }
            //你可以在此编写订单逻辑
            if(!empty($order)){
                $user=db('user')->where('id',$order['user_id'])->find();
                if($order['type']==1){
                    WalletService::change($user['id'], 'commission', $payamount, 'churujin', [
                        'mobile' => $user['mobile'],
                    ],'入金');
                }else{
                    $time=time();
                    $sign=base64_encode(md5($user['mobile'].$time.$payamount.'haibeisign159'));//验证方式
                    $time=strval($time);
                    $params=array(
                        'amount'=>$payamount,
                        'sign'=>$sign,
                        'time'=>$time,
                        'mobile'=>$user['mobile'],
                    );
                    $arr=json_encode($params);
                    $headers=array(
                        'Content-Type:application/json',
                        'Content-Length:'.strlen($arr),
                    );
                    $ret = Http::httpRequest('https://newhb.nfttop123.com:44303/api/app/member-card-client/store-chujin', 'POST',$arr,$headers);
                    // $ret = Http::sendRequest('https://hb.nfttop123.com:44303/api/app/member-card-client/store-chujin', $params, 'POST');
                    json_decode($ret,true);
                }

                db('shopro_chongzhi')->where('pay_sn',$out_trade_no)->update(['status'=>'paid']);

            }

            // 支付成功后续使用异步队列处理
           // \think\Queue::push('\addons\shopro\job\OrderPaid@paid', ['order' => $order, 'user' => $user], 'shopro-high');

        } catch (Exception $e) {
           // var_dump($e->getMessage());
        }

        //下面这句必须要执行,且在此之前不能有任何输出

        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }

    /**
     * 支付返回，仅供开发测试
     */
    public function returnx()
    {
        $paytype = $this->request->param('paytype');
        $out_trade_no = $this->request->param('out_trade_no');
        $pay = Service::checkReturn($paytype);
        if (!$pay) {
            $this->error('签名错误', '');
        }

        //你可以在这里通过out_trade_no去验证订单状态
        //但是不可以在此编写订单逻辑！！！

        $this->success("请返回网站查看支付结果", addon_url("epay/index/index"));
    }

}
